<template>
    <div class="flex flex-row justify-between align-center w-full">
        <div v-if="showBtn" class="flex"><el-button link class="mx-1" @click="overflow('left')">
                <Left theme="outline" size="16" fill="#515a6e" />
            </el-button></div>
        <div ref="menuRefContainer"
            class="flex-1 overflow-x-auto [&::-webkit-scrollbar]:hidden grid grid-flow-col auto-cols-min scroll-smooth">
            <div ref="menuRef" class="flex ">
                <el-button link :type="activeRoute === item.path ? 'primary' : ''" @click="toRoute(item.path)"
                    class="!bg-[#ffffff] dark:!bg-[#1d1e1f]  rounded-sm !px-3 !ml-2 first:!ml-0"
                    :ref="(el: HTMLElement) => setButtonRef(el, item)" v-for="(item, index) in activeMenu">{{
                        item.title }}
                    <el-button link size="small" class="!p-0 ml-1 " v-if="index !== 0">
                        <Close theme="outline" size="10" color="#636e85" hover-color="#fff" @click="removeMenu(item)" />
                    </el-button>
                </el-button>
            </div>
        </div>
        <div v-if="showBtn" class="flex"><el-button link class="mx-1" @click="overflow('right')">
                <Right theme="outline" size="16" fill="#515a6e" />
            </el-button></div>
        <div class="flex"><el-dropdown @command="handleCloseNavBar">
                <span class="bg-white dark:bg-[#1d1e1f] p-2 rounded-sm ">
                    <Down theme="outline" size="14" fill="#515a6e" />
                </span>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item command="left">
                            <LeftSmall class="mr-2" theme="outline" size="12" fill="#515a6e" />关闭左侧
                        </el-dropdown-item>
                        <el-dropdown-item command="right">
                            <RightSmall class="mr-2" theme="outline" size="12" fill="#515a6e" />关闭右侧
                        </el-dropdown-item>
                        <el-dropdown-item command="other">
                            <CloseSmall class="mr-2" theme="outline" size="12" fill="#515a6e" />关闭其他
                        </el-dropdown-item>
                        <el-dropdown-item command="all">
                            <CloseOne class="mr-2" theme="outline" size="12" fill="#515a6e" />关闭全部
                        </el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown></div>
    </div>
</template>

<script setup lang="ts">
import { ref, watch, nextTick, computed, onMounted, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Left, Right, Down, LeftSmall, RightSmall, CloseSmall, Close, CloseOne } from '@icon-park/vue-next'


const menuRef = ref<HTMLElement | null>(null)
const menuRefContainer = ref<HTMLElement | null>(null)
const buttonRefs = ref<Record<string, HTMLElement>>({})
const route = useRoute()
const router = useRouter()

interface menuItem {
    title: string | unknown
    path: string
}

const activeMenu = ref<menuItem[]>([{ title: '仪表盘', path: '/dashboard' }])

const activeRoute = computed(() => {
    return route.path
})
const showBtn = ref(false)
const widthDiffs = () => {
    const parentWidth = menuRefContainer.value!.clientWidth
    const childwidth = menuRef.value!.clientWidth

    if (childwidth > parentWidth) {
        showBtn.value = true
        // overflow('right')
    } else {
        showBtn.value = false
    }

}
const setButtonRef = (el: HTMLElement, item: any) => {

    if (el) {
        // 获取原生DOM元素（如果是组件实例，则获取其$el）
        // @ts-ignore
        buttonRefs.value[item.path] = el.$el
    }
}
// 检查按钮是否在可视区域内
const isElementInViewport = (el: HTMLElement, container: HTMLElement) => {

    const containerRect = container.getBoundingClientRect()
    const elRect = el.getBoundingClientRect()

    return (
        elRect.left >= containerRect.left &&
        elRect.right <= containerRect.right
    )
}

const scrollToButton = (path: string) => {
    nextTick(() => {

        if (!menuRefContainer.value || !buttonRefs.value[path]) return

        const container = menuRefContainer.value
        const button = buttonRefs.value[path]

        if (!isElementInViewport(button, container)) {
            // 计算需要滚动的距离
            const containerRect = container.getBoundingClientRect()
            const buttonRect = button.getBoundingClientRect()

            if (buttonRect.left < containerRect.left) {
                // 按钮在左侧不可见，滚动到左侧
                const diffs = containerRect.left - buttonRect.left

                container.scrollLeft -= (containerRect.left - buttonRect.left)
            } else if (buttonRect.right > containerRect.right) {
                // 按钮在右侧不可见，滚动到右侧
                container.scrollLeft += (buttonRect.right - containerRect.right)

            }
        }
    })
}
const handleCloseNavBar = (command: string) => {
    const index = activeMenu.value.findIndex(item => item.path === route.path)
    if (index === -1) {
        return activeMenu.value;
    }


    switch (command) {
        case 'left':
            // 删除左边的元素，保留第一项和目标对象
            activeMenu.value.splice(1, index - 1);
            break;
        case 'right':
            // 删除右边的元素，保留第一项和目标对象
            activeMenu.value.splice(index + 1);
            break;
        case 'other':
            // 删除除目标对象以外的元素，只保留第一项和目标对象
            const temp = activeMenu.value[index];
            activeMenu.value.splice(1)
            activeMenu.value.push(temp);
            break;
        case 'all':
        default:
            // 删除除第一项以外的元素
            activeMenu.value.splice(1);
            router.push(activeMenu.value[0].path)
            break;
    }

}

const removeMenu = (value: menuItem) => {
    const index = activeMenu.value.findIndex(item => item.path === value.path)
    if (index == activeMenu.value.length - 1) {
        router.push(activeMenu.value[index - 1].path)
    } else {
        router.push(activeMenu.value[index + 1].path)
    }
    activeMenu.value.splice(index, 1)


    nextTick(() => {
        widthDiffs()
    })
}
const overflow = (value: string) => {
    if (value === 'right') {
        if (menuRefContainer.value) {
            requestAnimationFrame(() => {
                const diffs = menuRef.value!.clientWidth - menuRefContainer.value!.clientWidth
                menuRefContainer.value!.scrollLeft += diffs

            });

        }
    } else {
        if (menuRefContainer.value) {
            requestAnimationFrame(() => {
                const diffs = menuRef.value!.clientWidth - menuRefContainer.value!.clientWidth
                menuRefContainer.value!.scrollLeft -= diffs

            })
        }
    }
}

const toRoute = (path: string) => {
    router.push(path)
}

watch(() => route.path, async (newPath) => {

    const active = {
        path: newPath,
        title: route.meta.title
    }
    if (!activeMenu.value.some(item => item.path === active.path)) {
        activeMenu.value.push(active)
    }
    // activeMenu.value.push(active)

    await nextTick()
    widthDiffs()
    scrollToButton(newPath)
}, { immediate: true })


</script>
<style scoped></style>